package com.cxh.rmsq.ui.widget

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.VelocityTracker
import androidx.core.widget.NestedScrollView
import com.amap.api.maps.MapView
import com.cxh.rmsq.R
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import java.lang.Math.abs

class MapCompatibleRefreshLayout(context: Context, attrs: AttributeSet) :
    SmartRefreshLayout(context, attrs) {

    private var initialX = 0f
    private var initialY = 0f
    private var isMapDragging = false

    // 核心方法：控制事件拦截
    override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
        val mapView = findMapViewChild()

        when (ev.action) {
            MotionEvent.ACTION_DOWN -> {
                initialX = ev.x
                initialY = ev.y
                isMapDragging = false
            }

            MotionEvent.ACTION_MOVE -> {
                mapView?.let {
                    if (isTouchOnMap(it, ev)) {
                        val dx = abs(ev.x - initialX)
                        val dy = abs(ev.y - initialY)

                        // 策略1：优先处理地图操作
                        if (dx > dy || ev.pointerCount >= 2) {
                            isMapDragging = true
                            return false // 不拦截，交给地图
                        }

                        // 策略2：动态分配惯性滑动
                        if (isInertialScroll(mapView, ev)) {
                            return super.onInterceptTouchEvent(ev)
                        }
                    }
                }
            }
        }

        return if (isMapDragging) false else super.onInterceptTouchEvent(ev)
    }

    // 查找嵌套的 MapView
    private fun findMapViewChild(): MapView? {
        val scrollView = mRefreshContent.view.findViewById<NestedScrollView>(R.id.nestedScrollView)
        return scrollView?.findViewById(R.id.mapview)
    }

    // 判断是否为地图惯性滑动
    private fun isInertialScroll(mapView: MapView, ev: MotionEvent): Boolean {
        val velocityTracker = VelocityTracker.obtain()
        velocityTracker.addMovement(ev)
        velocityTracker.computeCurrentVelocity(1000)
        val yVelocity = abs(velocityTracker.yVelocity)
        velocityTracker.recycle()
        return yVelocity > 2000 // 速度阈值，单位：像素/秒
    }

    // 判断触摸点是否在地图上
    private fun isTouchOnMap(mapView: MapView, ev: MotionEvent): Boolean {
        val location = IntArray(2)
        mapView.getLocationOnScreen(location)
        val rect = Rect(
            location[0],
            location[1],
            location[0] + mapView.width,
            location[1] + mapView.height
        )
        return rect.contains(ev.rawX.toInt(), ev.rawY.toInt())
    }
}